
package es.upm.dit.gsi.opactv;

import es.upm.dit.gsi.opactv.searchengines.Amazon;
import es.upm.dit.gsi.opactv.searchengines.CAM;
import es.upm.dit.gsi.opactv.searchengines.LibraryThing;
import es.upm.dit.gsi.opactv.searchengines.Librofilia;
import es.upm.dit.gsi.opactv.searchengines.SearchEngine;
import es.upm.dit.gsi.opactv.util.JSON;
import java.util.ArrayList;
import java.util.Random;

public class Session {

    private ArrayList<SearchEngine> searchEngines = new ArrayList();
    private ArrayList<Book> books = new ArrayList();
    private JSON json = new JSON();
    private String sessionID = generateSID();

    public Session() {
        searchEngines.add(new CAM());
        searchEngines.add(new Amazon());
        searchEngines.add(new Librofilia());
        searchEngines.add(new LibraryThing());
    }

    public String getBooks(String title, String author, String tags) {
        books = new ArrayList();
        for (SearchEngine engine : searchEngines) {
            engine.set(title, author, tags);
            addBooks(engine.getBooks());
        }
        return json.booksToJSON(books);
    }

    public String getBook(int id) {
        if (id<0 || id>=books.size()) {
            return json.errorToJSON("invalid_param" , "The ID param is invalid");
        }
        Book book = books.get(id);
        for (SearchEngine engine : searchEngines) {
            engine.completeBook(book);
        }
        return json.bookToJSON(book);
    }

    public String getSID() {
        return sessionID;
    }
    
    private void addBooks(ArrayList<Book> books) {
        for (Book book : books) this.books.add(book);
    }

    private String generateSID() {
        String characters = "0123456789abcdefghijklmnopqrstuvwxyz" +
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(32);
        for(int i=0; i<32; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }

}
